package com.tianjishuju.cimiss.station.station.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * @author Blithe.Lee
 *
 */
public class FileUtil {

    /**
     * 文件探针 当父目录不存在时，创建目录！
     *
     * @param dirFile
     */
    public final static void fileProber(File dirFile) {
        int index = dirFile.getName().indexOf(".");

        if (index == -1) dirFile.mkdirs();
        else dirFile.getParentFile().mkdirs();
    }

    /**
     * 获取文件扩展名
     * @param fileName
     * @return
     */
    public final static String getFileExt(String fileName) {
        int len = fileName.lastIndexOf(".");
        return len == -1? null: fileName.substring(len);
    }

    /**
     * 获取文件扩展名
     * @param file
     * @return
     */
    public final static String getFileExt(File file) {
        return getFileExt(file.getName());
    }

    /**
     * 获取文件名，不包含扩展名
     * @param fileName
     * @return
     */
    public final static String getFileName(String fileName) {
        int len = fileName.indexOf(".");
        return len == -1? fileName: fileName.substring(0, len);
    }

    public final static boolean deleteFile(String filePath){
        return deleteFile(new File(filePath));
    }

    public final static boolean deleteFile(File file){
        if(file == null || !file.exists())
            return true;

        if(file.isDirectory()){
            File[] files = file.listFiles();
            for (File f : files) {
                deleteFile(f);
            }
        }
        return file.delete();
    }

	  /*
	    *按行读取文件 key|value
	    */
	    public static HashMap<String,String> readFile(String filePath) {
	        File file = new File(filePath);
	        HashMap<String,String> FilePathList = new HashMap<String,String>();
	        BufferedReader reader = null;
	        try {
	            reader = new BufferedReader(new FileReader(file));
	            String tempString = null;
	            while ((tempString = reader.readLine()) != null) {
	            	String[] ts = tempString.replace("\n", "").split(":");
	            		FilePathList.put(ts[0],ts[1]);
	            }
	            reader.close();
	        } catch (IOException e) {
	            e.printStackTrace();
	        } finally {
	            if (reader != null) {
	                try {
	                    reader.close();
	                } catch (IOException e1) {
	                }
	            }
	        }
	        return FilePathList;
	    }
	    
	    /*
	    *以追加方式写文件
	    */
	    public static void writeFile(String filePath, String conent) {
	        BufferedWriter out = null;
	        try {
	            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath, true)));
	            out.write(conent);
	        } catch (Exception e) {
	            e.printStackTrace();
	        } finally {
	            try {
	                if (out != null) {
	                    out.close();
	                }
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
	        }
	    }
	    
	    /*
	    *创建文件
	    */
	    public static void createFile(String filePath) {
	        File file = new File(filePath);
	        if (file.exists()) {
	            //System.out.println("文件已存在");
	        } else {
	            try {
	                File fileParent = file.getParentFile();
	                if (fileParent != null) {
	                    if (!fileParent.exists()) {
	                        fileParent.mkdirs();
	                    }
	                }
	                file.createNewFile();
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
	        }
	    }
	    
	    /*
	    *以追加方式写文件，效率低
	    */
	    public static void writeFileByFileWriter(String filePath, String content) {
	        FileWriter writer = null;
	        try {
	            writer = new FileWriter(new File(filePath), true);
	            writer.write(content);
	        } catch (IOException e) {
	            e.printStackTrace();
	        } finally {
	            try {
	                if (writer != null) {
	                    writer.close();
	                }
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
	        }
	    }
	    private static ArrayList<String> dirctorys;

		/*
		 * 递归调用查找指定文件加下所有文件
		 */
		public static ArrayList<String> GetSql(String path) {
			File rootDir = new File(path);

			if (!rootDir.isDirectory()) {
				System.out.println(rootDir.getAbsolutePath());
				String arr = rootDir.getAbsolutePath();
				dirctorys.add(arr);
			} else {
				String[] fileList = rootDir.list();
				for (int i = 0; i < fileList.length; i++) {
					if (!fileList[i].substring(0, 1).equals(".")) {
						path = rootDir.getAbsolutePath() + "/" + fileList[i];
						GetSql(path);
					}
				}
			}
			return dirctorys;
		}

		/**
	     * 获取路径下的所有文件/文件夹
	     * @param directoryPath 需要遍历的文件夹路径
	     * @param isAddDirectory 是否将子文件夹的路径也添加到list集合中
	     * @return
	     */
	    public static ArrayList<String> getAllFile(String directoryPath,boolean isAddDirectory) {
	    	ArrayList<String> list = new ArrayList<String>();
	        File baseFile = new File(directoryPath);
	        if (baseFile.isFile() || !baseFile.exists()) {
	            return list;
	        }
	        File[] files = baseFile.listFiles();
	        for (File file : files) {
	            if (file.isDirectory()) {
	                if(isAddDirectory){
	                    list.add(file.getAbsolutePath());
	                }
	                list.addAll(getAllFile(file.getAbsolutePath(),isAddDirectory));
	            } else {
	                list.add(file.getAbsolutePath());
	            }
	        }
	        return list;
	    }
		
		
		public static void main(String args[]) {
			ArrayList<String> dc = new ArrayList<String>(); 
			String filepath = "/test/app/flink/data/cimissfile/eric";
			dc =  getAllFile(filepath,true);
			for (String string : dc) {
				if(!getFileNameWithSuffix(string).startsWith("."))
				System.out.println(string);
			}
		}
	    /** 
	     * 保留文件名及后缀 
	     */  
	    public static String getFileNameWithSuffix(String pathandname) {         
	        int start = pathandname.lastIndexOf("/");  
	        if (start != -1 ) {  
	            return pathandname.substring(start + 1);  
	        } else {  
	            return null;  
	        }         
	    }  
	    /**
	     * 返回路径 不包含斜杠 /1/2
	     */
	    public static String getFilePath(String pathandname){
	    	int start = pathandname.lastIndexOf("/");  
	        if (start != -1 ) {  
	            return pathandname.substring(0, start);  
	        } else {  
	            return null;  
	        }   
	    }
}
